<script setup>
import { userUpdateInfoService } from '@/api/user'
import { useUserStore } from '@/stores'
// 初次渲染，解构赋值即可
const {
  user: { id, username, nickname, email }
} = useUserStore()

const formModel = ref({
  id,
  username,
  nickname,
  email
})

const rules = {
  nickname: [
    { required: true, message: '请输入用户昵称', trigger: 'blur' },
    {
      pattern: /^\S{1,10}$/,
      message: '昵称为 1-10 位非空格字符',
      trigger: 'blur'
    }
  ],
  email: [
    { required: true, message: '请输入用户邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ]
}

const formRef = ref()
const handleSubmit = async () => {
  // 提交前先进行表单校验
  const valid = await formRef.value.validate()
  if (valid) {
    // 提交表单
    await userUpdateInfoService(formModel.value)
    // 提交成功后，重新获取用户信息
    useUserStore().getUser()
    ElMessage.success('修改成功')
  }
}
</script>

<template>
  <Page-container title="基本资料">
    <el-row>
      <el-col :span="12">
        <el-form
          :model="formModel"
          label-width="100px"
          :rules="rules"
          ref="formRef"
          size="large"
        >
          <el-form-item label="登录名称">
            <el-input v-model="formModel.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="用户昵称" prop="nickname">
            <el-input v-model="formModel.nickname"></el-input>
          </el-form-item>
          <el-form-item label="用户邮箱" prop="email">
            <el-input v-model="formModel.email"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSubmit">提交修改</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </Page-container>
</template>
